<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 代金券 统计
 * Class postal_card
 */
class Coupon extends MY_Controller {
    /**
     * @var ConsumerPromotionModel
     */
    public $mCPromotion = null;
    /**
     * @var MerchantPromotionModel
     */
    public $mMPromotion = null;
    /**
     * @var MerchantUserModel
     */
    public $mMerchant = null;

	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerPromotionModel', 'mCPromotion', 'consumer');
		$this->loadModel('MerchantPromotionModel', 'mMPromotion', 'merchant');
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        // 最近1个月
        $startTime = strtotime("-1 month");

        $data = array(
            'startTime' => dateFormat($startTime),
            'endTime' => dateFormat(time()),
        );
		$this->view('statistics/coupon', $data, 'datatable,date_range_picker');
	}

    /**
     * 获取数据
     */
    public function getList(){
        $data = $this->lists();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = $v['send_number'];
            $data['aaData'][$k][] = $v['used'];
            $data['aaData'][$k][] = $v['not_used'];
            $data['aaData'][$k][] = $v['use_end'];
            $data['aaData'][$k][] = isset($v['used_money']) ? $v['used_money'] : 0;
            $data['aaData'][$k][] = $v['total_money'];
            $data['aaData'][$k][] = dateFormat($v['use_end_time']);
            $data['aaData'][$k][] = dateFormat($v['addtime']);
        }
        unset($data['data']);
        echo json_encode($data);
    }

    public function lists($page = 0, $pageNumber = 0){
            $timeGap = trim(get('timegap'));
            $type = (int)get('type');
            if (!isset($timeGap)){
                // 最近1个月
                $startTime = strtotime("-1 month");
                $endTime = 0;
            }else{
                $timeGapArr = explode(' - ', $timeGap);
                $startTime = strtotime($timeGapArr[0]);
                $endTime = strtotime($timeGapArr[1]);
            }

            $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
            $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

            if ($type){
                $this->db->where('b.type >= '.$type);
            }
            if ($startTime){
                $this->db->where('b.addtime >= '.$startTime);
            }
            if ($endTime){
                $endTime = strtotime('+1 day', $endTime);
                $this->db->where('b.addtime < '.$endTime);
            }

            if ($iSortCol_0 == 2){
                $this->db->order_by('b.money', $sSortDir_0); // 红包金额
            }else if($iSortCol_0 == 3){
                $this->db->order_by('b.send_number', $sSortDir_0); // 发布数量
            }else if($iSortCol_0 == 4){
                $this->db->order_by('used', $sSortDir_0); // 使用数量
            }else if($iSortCol_0 == 5){
                $this->db->order_by('not_used', $sSortDir_0); // 未使用数量
            }else if($iSortCol_0 == 6){
                $this->db->order_by('use_end', $sSortDir_0); // 失效数量
            }else if($iSortCol_0 == 7){
                $this->db->order_by('used_money', $sSortDir_0); // 使用金额
            }else if($iSortCol_0 == 8){
                $this->db->order_by('total_money', $sSortDir_0); // 红包金额
            }else if($iSortCol_0 == 9){
                $this->db->order_by('b.addtime', $sSortDir_0); // 红包金额
            }
            $t = strtotime(date('Y-m-d', time()));
            $this->db->select('s.shop_name as name,b.money,count(bl.id) as send_number,
                count(if(bl.status = 1, bl.status, null)) as not_used,count(if(bl.status = 2, bl.status, null)) as used,
                sum(if(bl.status = 2, bl.money, null)) as used_money,sum(bl.money) as total_money,b.addtime,bl.use_end_time,
                count(if(bl.status != 2 and bl.use_end_time < '.$t.', bl.id, null)) as use_end')
                ->join($this->mCPromotion->tbCashCoupon.' bl', 'b.merchant_id=bl.merchant_id')
                ->join($this->mMerchant->tbUser.' m', 'm.id=b.merchant_id')
                ->join($this->mMerchant->tbShop.' s', 'm.id=s.merchant_id')
                ->where('m.status > -1')
                ->group_by('b.merchant_id');
            if ($page && $pageNumber) {
                $tA = $this->mCPromotion->appPage($this->mMPromotion->tbCashCoupon.' b', $page, false, $pageNumber);
                return $tA['list'];
            }else{
                return $this->mCPromotion->pagination($this->mMPromotion->tbCashCoupon.' b');
            }
    }

    /**
     * 导出
     * @author defcu
     */
    public function export(){
        $timeGap = trim(get('timegap'));
        $timeGapArr = explode(' - ', $timeGap);
        $filename = '代金券统计'.$timeGapArr[0].'-'.$timeGapArr[1].'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('名称,发放金额,发放数量,使用数量,未使用数量,失效数量,使用总金额,发放总金额,截至时间,发放时间','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $list = $this->lists($page, $pageNumber);
            if(empty($list)){
                break;
            }
            $page ++;
            foreach($list as $v){
                $used_money = isset($v['used_money']) ? $v['used_money'] : 0;
                echo mb_convert_encoding($v['name'].','.$v['money'].','.$v['send_number'].','.$v['used'].','.$v['not_used'].','.$v['use_end'].','.$used_money.','. $v['total_money'].','. dateFormat($v['use_end_time']).','. dateFormat($v['addtime']), 'gb2312','utf-8')."\n";
            }
        }
    }
}
